<?php


namespace App\Http\Util;

use App\Models\Account;
use App\Models\AllExam;
use App\Models\OperateChild;
use App\Models\OperateQuestion;
use App\Models\OperGroup;
use App\Models\QuestionCategory;
use App\Models\Roles;
use App\Models\Sign;
use App\Models\WeMenus;
use Illuminate\Support\Facades\Redis;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use function GuzzleHttp\json_decode;
use Illuminate\Support\Str;

class Wechat
{
    public static function getAccessToken(){
        if(Redis::exists('WECHAT_TOKEN')){
            return Redis::get('WECHAT_TOKEN');
        }
        $appid ='wx5fb830b234320db1';
        $secret = 'df3727e7cae40c0c6d2c9b418edc69f1';
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $data['grant_type'] = 'client_credential';
        $data['appid'] = $appid;
        $data['secret'] = $secret;
        $data = self::wxpost($url,$data);
        $resultArr = json_decode($data, true);//转为数组
        Redis::setex('WECHAT_TOKEN',7200, $resultArr["access_token"]);
        return $resultArr["access_token"];//获取access_token
    }

    public static function curl_get($url){

        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);

        // 显示错误信息
        if (curl_error($curl)) {
            return "Error: " . curl_error($curl);
        } else {
            curl_close($curl);
            return json_decode($data,true);
        }
    }

    //创建菜单
    public function creatMenu($string){
        //获取access_token
        $accessToken = Redis::get('WECHAT_TOKEN');
        if(!$accessToken){
            $accessToken = self::getAccessToken();
        }

        //构造POST给微信服务器的菜单结构体
//        $menuPostString = '{
//        "button":[{
//                "name":"产品介绍",
//                "sub_button":[{
//                    "type":"view",
//                    "name":"分销A型",
//                    "url":"http://www.yourwebname.com/fenxiao/jianjie/soft.html"
//                },{
//                    "type":"view",
//                    "name":"分销B型",
//                    "url":"http://www.yourwebname.com/fenxiaob/jianjie/soft.html"
//                },{
//                    "type":"view",
//                    "name":"地接批发",
//                    "url":"http://www.yourwebname.com/dijie/jianjie/soft.html"
//                },{
//                    "type":"view",
//                    "name":"精简组团",
//                    "url":"http://www.yourwebname.com/zutuan/jianjie/soft.html"
//                },{
//                    "type":"view",
//                    "name":"直客网站",
//                    "url":"http://www.yourwebname.com/tripal/jianjie/soft.html"
//                }]
//            },{
//                "name":"申请试用",
//                    "sub_button":[{
//                    "type":"click",
//                    "name":"分销A型",
//                    "key":"event"
//                },{
//                    "type":"click",
//                    "name":"分销B型",
//                    "key":"fxb"
//                },{
//                    "type":"click",
//                    "name":"地接批发",
//                    "key":"dj"
//                },{
//                    "type":"click",
//                    "name":"精简组团",
//                    "key":"zutuan"
//                },{
//                    "type":"click",
//                    "name":"直客网站",
//                    "key":"zhike"
//                }]
//            },{
//              "name":"博纵在线",
//                "sub_button":[{
//                    "type":"view",
//                    "name":"企业介绍",
//                    "url":"http://www.yourwebname.com/about.html"
//                },{
//                    "type":"view",
//                    "name":"公司新闻",
//                    "url":"http://www.yourwebname.com/news/company/"
//                },{
//                    "type":"view",
//                    "name":"联系我们",
//                    "url":"http://www.yourwebname.com/contact.html"
//                }]
//            }
//        ]}';
        $menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken;//POST的url
        $menu = $this->wxpost($menuPostUrl,$string);
        $log = new Logger('openmenus');
        $log->pushHandler(new StreamHandler(storage_path('logs/openmenus.log'),Logger::INFO) );
        $log->notice(date('Y-m-d H:i:s').'-用户提交信息:'.$menu);

    }

    public function getMediaId(){
        $accessToken = Redis::get('WECHAT_TOKEN');
        if(!$accessToken){
            $accessToken = self::getAccessToken();
        }
        $menuPostUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$accessToken;//POST的url
        $data['type'] = 'image';
        $data['offset'] = 0;
        $data['count'] = 20;
        $menu = $this->wxpost($menuPostUrl,$data);
        print_r($menu);exit;
    }
//get https的内容
    public static function getCurl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//不输出内容
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close ($ch);
        return $result;
    }
//POST方式提交数据
    public static function dataPost($post_string, $url) {
        $context = array ('http' => array ('method' => "POST", 'header' => "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*", 'content' => $post_string ) );
        $stream_context = stream_context_create ( $context );
        $data = file_get_contents ( $url, FALSE, $stream_context );
        return $data;
    }

    public function wxpost($url,$post)
    {
        //初始化
        $curl = curl_init();
//        $header[] = "Content-type: text/json";//定义content-type为xml
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //定义请求类型
//        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        $post_data = $post;
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求

        //显示获得的数据
        if ($data)
        {
            curl_close($curl);
            return $data;
        }else{
            $res = curl_error($curl);
            curl_close($curl);
            return $res;
        }
    }



    public static function sendMessage($postData,$token){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
        return self::wxpost($url,$postData);
    }

}
